In [2]:
#Example_1: return keyword
def straight_line(slope,intercept,x):
"Computes straight line y value"
y = slope*x + intercept
return y
print("y =",straight_line(1,0,5)) #Actual Parameters
print("y =",straight_line(0,3,10))
#By default, arguments have a positional behaviour
#Each of the parameters here is called a formal parameter
In [3]:
#Example_2
def straight_line(slope,intercept,x):
y = slope*x + intercept
print(y)
straight_line(1,0,5)
straight_line(0,3,10)
#By default, arguments have a positional behaviour
#Functions can have no inputs or return.
In [4]:
straight_line(x=2,intercept=7,slope=3)
In [5]:
list_zeroes=[0 for x in range(0,5)]
print(list_zeroes)
In [6]:
def case1(list1):
list1[1]=1
print(list1)
case1(list_zeroes)
print(list_zeroes)
In [7]:
#Passing variables to a function
list_zeroes=[0 for x in range(0,5)]
print(list_zeroes)
In [8]:
def case2(list1):
list1=[2,3,4,5,6]
print(list1)
case2(list_zeroes)
print(list_zeroes)
In [1]:
def calculator(num1,num2,operator='+'):
if (operator == '+'):
result = num1 + num2
elif(operator == '-'):
result = num1 - num2
return result
n1=int(input("Enter value 1: "))
n2=int(input("Enter value 2: "))
v_1 = calculator(n1,n2)
print(v_1)
v_2 = calculator(n1,n2,'-')
print(v_2)
# Here, the function main is termed as the caller function, and the function
# calculator is termed as the called function
# The operator parameter here is called a keyword-argument
In [10]:
def f(a, L=[]):
L.append(a)
return L
print(f(1))
print(f(2))
print(f(3))
# Caution ! The list L[] was initialised only once.
#The paramter initialization to the default value happens at function definition and not at function call.
In [2]:
def sum(*values):
s = 0
for v in values:
s = s + v
return s
s = sum(1, 2, 3, 4, 5)
print(s)
In [3]:
def get_a(**values):
return values['a']
s = get_a(a=1, b=2) # returns 1
print(s)
In [4]:
def sum(*values, **options):
s = 0
for i in values:
s = s + i
if "neg" in options:
if options["neg"]:
s = -s
return s
s = sum(1, 2, 3, 4, 5) # returns 15
print(s)
s = sum(1, 2, 3, 4, 5, neg=True) # returns -15
print(s)
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15
print(s)
In [ ]: